<template>
  <div class='container'>
    <!-- 卡片区域 -->
    <el-card>
      <el-breadcrumb separator-class="el-icon-arrow-right" v-if="$route.query.id!==undefined">
        <el-breadcrumb-item>学科管理</el-breadcrumb-item>
        <el-breadcrumb-item>{{routeSubjectName}}</el-breadcrumb-item>
        <el-breadcrumb-item>标签管理</el-breadcrumb-item>
      </el-breadcrumb>
      <el-row>
        <el-col :span="18">
          <el-form :inline="true" :model="queryInfo" ref="dirFormRef">
            <el-form-item label="目录名称" prop="directoryName">
              <el-input size="small" clearable v-model.trim="queryInfo.directoryName"></el-input>
            </el-form-item>
            <el-form-item label="状态" prop="state">
              <el-select v-model="queryInfo.state" placeholder="请选择" size="small">
                <el-option label="启用" value="1"></el-option>
                <el-option label="禁用" value="0"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button size="small" @click="clear">清空</el-button>
              <el-button type="primary" size="small" @click="getDirestorys">搜索</el-button>
            </el-form-item>
          </el-form>
        </el-col>
        <el-col :span="6">
          <el-button style="float: right; padding: 10px" type="success" icon="el-icon-edit" size="small"
            @click="addDirectorys">新增目录
          </el-button>
          <el-button type="text" style="float: right; padding: 10px" v-if="$route.query.id!==undefined"
            @click="skipSubject" icon="el-icon-back">返回学科</el-button>
        </el-col>
      </el-row>
      <!-- 消息提示区域 -->
      <el-alert type="info" show-icon :closable="false" class="alret">
        <div slot="title">数据一共 {{ total }} 条</div>
      </el-alert>
      <!--/ 消息提示区域 -->

      <!-- 数据操作 -->
      <el-table :data="directList" stripe style="width: 100%">
        <el-table-column type="index" label="序号" width="80px"></el-table-column>
        <el-table-column prop="subjectName" label="所属学科"> </el-table-column>
        <el-table-column prop="directoryName" label="目录名称">
        </el-table-column>
        <el-table-column prop="username" label="创建者"></el-table-column>
        <el-table-column prop="addDate" label="创建日期">
          <template slot-scope="scope">
            {{ scope.row.addDate | parseTimeByString }}
          </template>
        </el-table-column>
        <el-table-column prop="totals" label="面试题数量"></el-table-column>
        <el-table-column prop="state" label="状态">
          <template slot-scope="scope">
            <div>{{ scope.row.state === 1 ? "已启用" : "已禁用" }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="state" label="操作">
          <template slot-scope="scope">
            <el-button type="text" @click="changeState(scope.row)">
              <div>{{ scope.row.state === 0 ? "启用" : "禁用" }}</div>
            </el-button>
            <el-button type="text" :disabled="scope.row.state === 1" @click="editRedirect(scope.row)">修改</el-button>
            <el-button type="text" :disabled="scope.row.state === 1" @click="deleteRedirect(scope.row.id)">删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 数据操作 -->
      <!-- 分页 -->
      <el-pagination background class="page" @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page.sync="queryInfo.pagenum" :page-sizes="[2, 5, 10]" :page-size="queryInfo.pagesize"
        layout="prev, pager, next, sizes, jumper" :total="total" style="margin-top: 20px; text-align: right;">
      </el-pagination>
      <!-- / 分页 -->
    </el-card>
    <!-- 添加对话框 -->
    <el-dialog title="新增目录" :visible.sync="dialogAdd" width="400px" @close="handleClose">
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px">
        <el-form-item label="所属学科" size="small" prop="subjectID" v-if="!routeId">
          <el-select v-model="addForm.subjectID" placeholder="请选择所属学科">
            <!-- 遍历目录列表渲染下拉菜单 -->
            <el-option v-for="item in subjectList" :key="item.id" :label="item.subjectName" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="目录名称" size="small" prop="directoryName">
          <el-input v-model="addForm.directoryName" placeholder="请输入目录名称"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogAdd = false">取 消</el-button>
        <el-button type="primary" @click="dialogAddForm">确 定</el-button>
      </span>
    </el-dialog>
    <!-- /添加对话框 -->
    <!-- 修改对话框  -->
    <el-dialog title="修改目录" :visible.sync="dialogEdit" width="400px" @close="changeClose">
      <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="100px">
        <el-form-item label="所属学科" size="small" prop="subjectID">
          <el-select v-model="editForm.subjectID">
            <el-option v-for="item in subjectList" :key="item.id" :label="item.subjectName" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="目录名称" size="small" prop="directoryName">
          <el-input v-model="editForm.directoryName"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogEdit = false">取 消</el-button>
        <el-button type="primary" @click="dialogEditForm">确 定</el-button>
      </span>
    </el-dialog>
    <!-- / 修改对话框  -->
  </div>
</template>

<script>
import { list, add, changeState, remove, update } from '@/api/hmmm/directorys.js'
// 重新把list命名为subject避免冲突
import { list as subjects } from '@/api/hmmm/subjects.js'
export default {
  data () {
    return {
      // 接收的id和名称
      routeSubjectName: '',
      routeId: null,
      // 获取学科列表数据
      subjectList: [],
      // 获取目录列表数据
      directList: [],
      // 获取查询用户信息的参数
      queryInfo: {
        // 当前的页数，即页码
        page: 1,
        // 每页显示的数据条数
        pagesize: 10,
        subjectID: null,
        directoryName: null,
        state: null
      },
      // 总数据条数
      total: 0,
      // 添加对话框弹出层显示与隐藏
      dialogAdd: false,
      // 修改对话框弹出层显示与隐藏
      dialogEdit: false,
      // 添加表单数据对象
      addForm: {
        directoryName: '',
        subjectID: ''
      },
      // 验证添加表单的规则
      addFormRules: {
        directoryName: [
          { required: true, message: '请输入目录名称', trigger: 'blur' },
          { min: 1, max: 9, message: '长度在 1 到 9 个字符', trigger: 'blur' }
        ]
      },
      // 修改表单的验证规则
      editFormRules: {
        directoryName: [
          { required: true, message: '请输入目录名称', trigger: 'blur' },
          { min: 1, max: 9, message: '长度在 1 到 9 个字符', trigger: 'blur' }
        ]
      },
      // 修改表单数据对象
      editForm: {
        subjectID: '',
        directoryName: '',
        // 修改的数据id
        id: ''
      }
    }
  },
  methods: {
    // 点击跳转到学科页面
    skipSubject () {
      this.$router.push({ path: '/subjects/list' })
    },
    // 点击修改对话框修改确定按钮修改数据
    async dialogEditForm () {
      const res = await update(this.editForm)
      this.dialogEdit = false
      if (res.status !== 200) return this.$message.error('修改失败')
      this.$message.success('修改目录成功')
      this.getDirestorys()
      console.log(res)
    },
    // 修改功能点击修改拿到数据
    async editRedirect (row) {
      this.dialogEdit = true
      this.editForm.subjectID = row.subjectID
      this.editForm.directoryName = row.directoryName
      // await update(this.addForm)
      this.editForm.id = row.id
      console.log(row)
    },
    // 删除功能
    deleteRedirect (id) {
      // console.log(id)
      this.$confirm('此操作将永久删除该目录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const res = await remove({ id })
        console.log(res)
        if (res.status !== 200) return this.$message.error('删除失败')
        this.$message.success('删除成功')
        this.getDirestorys()
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 点击切换状态
    async changeState (row) {
      // console.log(row)
      const res = await changeState({ id: row.id, state: row.state === 0 ? 1 : 0 })
      console.log(res)
      row.state = row.state === 0 ? 1 : 0
      this.$message.success('操作成功')
    },
    // async changeState (set) {
    //   // set.state = !set.state
    //   try {
    //     await changeState({
    //       id: set.id,
    //       state: set.state === 0 ? 1 : 0
    //     })
    //     // 判定状态 0 的话变成1 或者0
    //     set.state = set.state === 0 ? 1 : 0
    //     this.$message.success('切换成功')
    //   } catch (err) {
    //     this.$message.error('切换失败')
    //   }
    // },
    // 关闭修改弹框自定义校验
    changeClose () {
      this.$refs.editFormRef.resetFields()
    },
    // 关闭新增弹框自定义校验
    handleClose () {
      this.$refs.addFormRef.resetFields()
      // this.addForm.subjectName = ''
    },
    // 确认提交表单 添加
    async dialogAddForm () {
      const res = await add(this.addForm)
      // console.log(res)
      if (res.status !== 200) return this.$message.error('失败')
      this.$message.success('新增目录成功')
      this.dialogAdd = false
      this.getDirestorys()
    },
    // 点击添加显示弹出框
    addDirectorys () {
      // console.log(this.addForm)
      // this.getDirestorys()
      this.dialogAdd = true
    },
    // 清空输入框和下拉框
    clear () {
      this.$refs.dirFormRef.resetFields()
      this.getDirestorys()
    },
    // 更新当前页数
    handleSizeChange (newSize) {
      this.queryInfo.pagesize = newSize
      // 重新发送请求，请求最新的数据
      this.getDirestorys()
    },
    // 更新当前页面
    handleCurrentChange (current) {
      this.queryInfo.page = current
      // 重新发送请求，请求最新的数据
      this.getDirestorys()
    },
    // 获取目录列表数据
    async getDirestorys () {
      const { data: res } = await list(this.queryInfo)
      // console.log(res)
      this.directList = res.items
      this.total = res.counts
    },
    // 获取学科数据
    async getSubjectList () {
      // console.log(123)
      const { data: res } = await subjects()
      // console.log(res)
      this.subjectList = res.items
    }

  },
  created () {
    this.getDirestorys()
    this.getSubjectList()
    // console.log(this.$route.query)
    this.routeId = this.$route.query.id
    this.routeSubjectName = this.$route.query.subjectName
    // this.addForm.subjectID = this.$route.query.id - 0
    if (this.$route.query.id !== undefined) {
      this.addForm.subjectID = this.$route.query.id - 0
    }
    // this.queryInfo.subjectID = this.$route.query.id - 0
    this.queryInfo.subjectID = (this.$route.query.id && +this.$route.query.id) || null
    // console.log(this.routeId !== '')
  }

}
</script>

<style scoped lang='less'>
.el-breadcrumb {
  margin-bottom: 20px;
  padding: 0 0 15px;
  border-bottom: 1px solid #dcdfe6;
}
.el-card {
  margin: 10px;
}
.el-alert {
  margin-bottom: 15px;
}
</style>
